// c++ standard lib
#include <cstring>
#include <iostream>

// head
#include "PeerList.h"

using namespace std;


bool PeerList::AddPeer(PEER_INFO *peer)
{
    if (GetPeer(peer->username) != nullptr) return false;

    // allocate space
    if (currrentSize >= totalSize)
    {
        PEER_INFO* temp = h_peerList;
        totalSize = totalSize * 2;
        h_peerList = new PEER_INFO[totalSize];
        memcpy(h_peerList, temp, currrentSize);
        delete temp;
    }

    // add peer to list
    memcpy(&h_peerList[currrentSize++], peer, sizeof(PEER_INFO));
    return true;
}

PEER_INFO *PeerList::GetPeer(char* username)
{
    for (int i = 0; i < currrentSize; i++)
    {
        if (strncasecmp(h_peerList[i].username, username, strlen(username)) == 0)
        {
            return &h_peerList[i];
        }
    }
    return nullptr;
}

void PeerList::DeletePeer(char* username)
{
    for (int i = 0; i < currrentSize; i++)
    {
        if (strcasecmp(h_peerList[i].username, username) == 0)
        {
            memcpy(&h_peerList[i], &h_peerList[i+1], (currrentSize - i - 1)*sizeof(PEER_INFO));
            currrentSize --;
            break;
        }
    }
}

void PeerList::DeleteAllPeers()
{
    currrentSize = 0;
}
